package com.scott.crm.base.interceptor.login;

import com.scott.crm.base.service.TokenService;
import com.scott.crm.base.utils.DataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 黄后林  解决所有的请求都拦截的问题
 * @version 1.0
 * @note
 * @date 2021-12-04 21:27:50
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("---------进入拦截器校验preHandle token---------");

        //OPTIONS
        String method = request.getMethod();
        log.info("---------method=["+method+"]---------");
        if (HttpMethod.OPTIONS.toString().equals(method)) {
            log.info("---------method=["+method+"]---------");
            return true;
        }

        //1、拿到token
        String token = request.getHeader("token");
        System.out.println("-----------拦截器中的token=["+token+"]-----------");

        boolean ck =tokenService.checkTokenAndTtl(token);
        if(ck){
            //说明token有效、继续进入Controller层
            return true;
        }else{
            log.info("---------token校验不通过---------");

            //给前端一点提示 不然前端就玩不动了
            DataUtil.hasNotLogin();

            response.setStatus(403);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(DataUtil.hasNotLogin().toString());
            return false;
        }
    }
}
